package cn.upfinder.allvideo.Activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.upfinder.allvideo.Adapter.VideoDetailPartsAdapter;
import cn.upfinder.allvideo.Contract.VideoDetailContact;
import cn.upfinder.allvideo.Presenter.VideoDetailPresenter;
import cn.upfinder.allvideo.R;
import cn.upfinder.allvideo.TBSWeb.X5WebView;
import cn.upfinder.datalibrary.Api.JXApi;
import cn.upfinder.datalibrary.Bean.VideoEntity;
import cn.upfinder.uilibrary.Adapter.BaseQuickAdapter;

public class VideoDetailActivity extends AppCompatActivity implements VideoDetailContact.View {
    private static final String TAG = VideoDetailActivity.class.getSimpleName();

    @BindView(R.id.rvVideoItems)
    RecyclerView rvVideoItems;
    @BindView(R.id.svContent)
    ScrollView svContent;
    @BindView(R.id.tvMovieDES)
    TextView tvMovieDES;
    @BindView(R.id.wvVideoPlayerInPager)
    X5WebView wvVideoPlayerInPager;
    @BindView(R.id.tvSelectedVideoEpisode)
    TextView tvSelectedVideoEpisode;
    @BindView(R.id.tvSelectedVideoDES)
    TextView tvSelectedVideoDES;
    @BindView(R.id.ivWebBack)
    ImageView ivWebBack;

    @BindView(R.id.tvWebTitle)
    TextView tvWebTitle;

    @BindView(R.id.ivWebRefresh)
    ImageView ivWebRefresh;
    @BindView(R.id.navigation1)
    LinearLayout navigation1;
    @BindView(R.id.progressBar1)
    ProgressBar progressBar1;
    @BindView(R.id.activity_video_detail)
    RelativeLayout activityVideoDetail;


    private WebViewClient webViewClient;
    private WebChromeClient webChromeClient;

    private Context context;
    private VideoDetailPresenter mvpPresenter;
    private VideoDetailPartsAdapter adapter;

    private VideoEntity videoEntity;

    public static final String BUNDLE_KEY = "bundlekey_video_data";

    private final int disable = 120;
    private final int enable = 255;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_detail);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {

        //设置x5WebView为开始为页面内全屏，点击全屏自定义 onShowCustomView()
        enablePageVideo();
        X5WebView.setSmallWebViewEnabled(true);
        //初始化进度条
        initProgressBar();


        //初始化WebView
        webViewClient = new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                return false;
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                changGoForwardButton(webView);

            }
        };

        webChromeClient = new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView webView, String title) {
                Log.d(TAG, "onReceivedTitle: " + title);
                tvWebTitle.setText("电影");
            }

            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                progressBar1.setProgress(newProgress);
                if (progressBar1 != null && newProgress != 100) {
                    progressBar1.setVisibility(View.VISIBLE);
                } else if (progressBar1 != null) {
                    progressBar1.setVisibility(View.GONE);
                }
            }

            View myVideoView;
            View myNormalView;
            IX5WebChromeClient.CustomViewCallback callback;

            @Override
            public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
                ScrollView normalView = (ScrollView) findViewById(R.id.svContent);
                ViewGroup viewGroup = (ViewGroup) normalView.getParent();
                viewGroup.removeView(normalView);
                viewGroup.addView(view);
                myVideoView = view;
                myNormalView = normalView;
                callback = customViewCallback;
            }


            @Override
            public void onHideCustomView() {
                if (callback != null) {
                    callback.onCustomViewHidden();
                    callback = null;
                }

                if (myVideoView != null) {
                    ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                    viewGroup.removeView(myVideoView);
                    viewGroup.addView(myNormalView);
                }
            }


        };

        wvVideoPlayerInPager.setWebViewClient(webViewClient);
        wvVideoPlayerInPager.setWebChromeClient(webChromeClient);


        context = this;
        mvpPresenter = (VideoDetailPresenter) getMvpPresenter();
        adapter = new VideoDetailPartsAdapter(R.layout.item_rv_videoparts, null);
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
//        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvVideoItems.setLayoutManager(new GridLayoutManager(context, 4));
        rvVideoItems.setHasFixedSize(true);
        rvVideoItems.setAdapter(adapter);
        adapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String url = adapter.getItem(position);

                //修改为页面内播放
                if (!url.isEmpty()) {
                    wvVideoPlayerInPager.loadUrl(JXApi.jxDefult1 + url);
                }
            }
        });

        if (getIntent() != null) {
            mvpPresenter.parseIntent(getIntent());
        } else {
            showError("Intent为空");
            return;
        }

    }



    private void initProgressBar() {
        progressBar1.setMax(100);
        progressBar1.setProgressDrawable(getResources().getDrawable(R.drawable.color_progressbar));
    }

    private void changGoForwardButton(WebView view) {
        if (view.canGoBack()) {
            ivWebBack.setAlpha(enable);
            ivWebBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    wvVideoPlayerInPager.goBack();
                }
            });
        } else {
            ivWebBack.setAlpha(enable);
            ivWebBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }

    }

    @Override
    public VideoDetailContact.Presenter getMvpPresenter() {
        if (mvpPresenter == null) {
            mvpPresenter = new VideoDetailPresenter(context, this);
        }
        return mvpPresenter;
    }

    @Override
    public void showError(String errorMsg) {

    }

    @Override
    public void showDetailData(VideoEntity videoEntity) {

        this.videoEntity = videoEntity;
        tvMovieDES.setText("简介：" + videoEntity.getDes());

        String defultUrl = videoEntity.getUrl();
        if (!defultUrl.isEmpty()) {
            String err = "http://jx.71ki.com/index.php?url=" + defultUrl;
            wvVideoPlayerInPager.loadUrl(JXApi.jxDefult1 + defultUrl);
        }

    }

    //显示选集
    @Override
    public void showParts(ArrayList<String> partsUrls) {
        adapter.setNewData(partsUrls);
    }

    private void enablePageVideo() {
        Log.i("jsToAndroid", "enablePageVideoFunc happend!");
        if (wvVideoPlayerInPager.getX5WebViewExtension() != null) {
            Toast.makeText(this, "页面内全屏播放模式", Toast.LENGTH_LONG).show();
            Bundle data = new Bundle();
            data.putBoolean("standardFullScreen", true);//true表示标准全屏，会调起onShowCustomView()，false表示X5全屏；不设置默认false，
            data.putBoolean("supportLiteWnd", true);//false：关闭小窗；true：开启小窗；不设置默认true，
            data.putInt("DefaultVideoScreen", 1);//1：以页面内开始播放，2：以全屏开始播放；不设置默认：1
            wvVideoPlayerInPager.getX5WebViewExtension().invokeMiscMethod("setVideoParams", data);
        }
    }

    //选择显示面板 1：选集 2：简介 3：其他
    //id :通过点击选择 viewId
    private void selectedShowTab(int id) {
        switch (id) {
            case R.id.tvSelectedVideoEpisode: //视频选集
                rvVideoItems.setVisibility(View.VISIBLE);
                tvMovieDES.setVisibility(View.GONE);
                tvSelectedVideoEpisode.setBackgroundColor(getResources().getColor(R.color.ios_btntext_blue));
                tvSelectedVideoDES.setBackgroundColor(getResources().getColor(R.color.text_gray));

                break;
            case R.id.tvSelectedVideoDES: //视频介绍
                rvVideoItems.setVisibility(View.GONE);
                tvMovieDES.setVisibility(View.VISIBLE);
                tvSelectedVideoEpisode.setBackgroundColor(getResources().getColor(R.color.text_gray));
                tvSelectedVideoDES.setBackgroundColor(getResources().getColor(R.color.ios_btntext_blue));
                break;
        }
    }

    @OnClick({R.id.tvSelectedVideoEpisode, R.id.tvSelectedVideoDES, R.id.ivWebBack, R.id.ivWebRefresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvSelectedVideoEpisode:
                selectedShowTab(view.getId());
                break;
            case R.id.tvSelectedVideoDES:
                selectedShowTab(view.getId());
                break;
            case R.id.ivWebBack:
                break;
            case R.id.ivWebRefresh:
                if (wvVideoPlayerInPager != null) {  //重载
                    wvVideoPlayerInPager.reload();
                }
                break;
        }
    }


}
